#!/bin/bash

# 1. 设置UTF-8编码
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

# 2. 定位项目根目录
find_root_dir() {
  local dir="$1"
  while [ "$dir" != "/" ]; do
    if [ -f "$dir/pubspec.yaml" ]; then
      echo "$dir"
      return 0
    fi
    dir=$(dirname "$dir")
  done
  return 1
}

root_dir=$(find_root_dir "$(pwd)")
if [ -z "$root_dir" ]; then
  echo -e "\033[31mERROR: Not in Flutter project\033[0m"
  exit 1
fi

# 3. 设置路径
SOURCE_DIR="$root_dir/lib/generated/translations/sources"
OUTPUT_FILE="$root_dir/lib/generated/translations/translations.dart"

# 4. 创建目录（如果不存在）
mkdir -p "$(dirname "$OUTPUT_FILE")"

# 5. 处理JSON文件
declare -A translations

process_json() {
  local file="$1"
  local lang_code=$(basename "$file" .json)
  declare -A nested_translations

  # 递归处理嵌套结构
  process_node() {
    local prefix="$1"
    local key="$2"
    local value="$3"

    local full_key
    if [ -z "$prefix" ]; then
      full_key="$key"
    else
      full_key="$prefix.$key"
    fi

    if [[ "$value" == {* ]]; then
      # 处理嵌套对象
      while IFS= read -r line; do
        if [[ "$line" == *\"*\":* ]]; then
          local child_key=$(echo "$line" | sed -E 's/^[[:space:]]*"([^"]+)":.*$/\1/')
          local child_value=$(echo "$line" | sed -E 's/^[[:space:]]*"[^"]+":(.*),?$/\1/')
          process_node "$full_key" "$child_key" "$child_value"
        fi
      done < <(echo "$value" | jq -c 'to_entries[]' | sed 's/\\"/\\\\"/g')
    else
      # 处理叶子节点
      nested_translations["$full_key"]=$(echo "$value" | sed -e 's/^"//' -e 's/"$//' -e "s/'/''/g")
    fi
  }

  # 读取并处理JSON文件
  while IFS= read -r line; do
    if [[ "$line" == *\"*\":* ]]; then
      key=$(echo "$line" | sed -E 's/^[[:space:]]*"([^"]+)":.*$/\1/')
      value=$(echo "$line" | sed -E 's/^[[:space:]]*"[^"]+":(.*),?$/\1/')
      process_node "" "$key" "$value"
    fi
  done < <(jq -c '.' "$file" | sed 's/\\"/\\\\"/g')

  # 将当前语言添加到主翻译字典
  for key in "${!nested_translations[@]}"; do
    translations["$lang_code.$key"]="${nested_translations[$key]}"
  done

  echo -e "\033[90mProcessed: $(basename "$file") (${#nested_translations[@]} keys)\033[0m"
}

# 处理所有JSON文件
for file in "$SOURCE_DIR"/*.json; do
  if [ -f "$file" ]; then
    process_json "$file"
  fi
done

# 6. 生成Dart文件
generate_dart_file() {
  echo "// GENERATED CODE - DO NOT MODIFY BY HAND"
  echo "// Generated at: $(date '+%Y-%m-%d %H:%M:%S')"
  echo
  echo "import 'package:get/get.dart';"
  echo
  echo "class AppTranslations extends Translations {"
  echo "  @override"
  echo "  Map<String, Map<String, String>> get keys => {"

  # 按语言代码分组
  declare -A lang_map
  for key in "${!translations[@]}"; do
    lang_code="${key%%.*}"
    trans_key="${key#*.}"
    lang_map["$lang_code.$trans_key"]="${translations[$key]}"
  done

  # 获取所有语言代码并排序
  lang_codes=($(printf '%s\n' "${!translations[@]}" | sed 's/\..*//' | sort -u))

  for lang_code in "${lang_codes[@]}"; do
    echo "    '$lang_code': {"

    # 提取当前语言的所有键值对并排序
    declare -A current_lang
    for key in "${!lang_map[@]}"; do
      if [[ "$key" == "$lang_code."* ]]; then
        trans_key="${key#*.}"
        current_lang["$trans_key"]="${lang_map[$key]}"
      fi
    done

    # 排序后输出
    sorted_keys=($(printf '%s\n' "${!current_lang[@]}" | sort))
    for key in "${sorted_keys[@]}"; do
      value="${current_lang[$key]}"
      echo "      '$key': '$value',"
    done

    echo "    },"
  done

  echo "  };"
  echo "}"
  echo
  echo "// 使用示例："
  echo "// GetMaterialApp("
  echo "//   translations: AppTranslations(),"
  echo "//   locale: Locale('zh', 'CN'),"
  echo "//   fallbackLocale: Locale('en', 'US'),"
  echo "// )"
}

# 7. 写入文件
if generate_dart_file > "$OUTPUT_FILE"; then
  echo -e "\033[32mSUCCESS: Generated translations.dart\033[0m"
  echo -e "\033[36mLocation: $OUTPUT_FILE\033[0m"
else
  echo -e "\033[31mERROR writing file\033[0m"
  exit 1
fi

exit 0